<style>
    .ck-editor__editable_inline {
        height: 400px !important;
    }
</style>
<article class="cl pd-20">
    <form action="" method="post" class="form form-horizontal" id="form-save">
        <input type="hidden" name="id" value="{$data.id}" id="id">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                <span class="c-red">*</span>标题:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <input type="text" class="input-text" value="{$data.title}" placeholder="请填写标题" id="title" name="title">
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                图片：</label>
            <div class="formControls col-xs-6 col-sm-4">
                <input type="text" class="input-text" value="{$data.titlepic}" name="titlepic" id="titlepic">
                <div style="width: 160px;height: 160px;">
                    <a href="javascript:void(0);" onclick="uploadPicture()">
                        <img id="view-titlepic"
                            src="{$data.titlepic ? $data.titlepic : '/static/images/upload_picture.png'}" alt="标题图"
                            title="{$data.titlepic ? '更换' : '添加'}标题图" style="max-width: 160px;max-height: 160px;">
                    </a>
                </div>
            </div>
            <label class="form-label col-xs-2 col-sm-2">
                <a class="btn btn-success radius" href="javascript:uploadPicture();">{$data.titlepic ? '更换' :
                    '添加'}标题图</a></label>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                关键词:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <input type="text" class="input-text" value="{$data.keywords}" placeholder="关键词" id="keywords"
                    name="keywords">
                <span class="c-red">多个关键词用英文','分割</span>
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">简介:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <textarea name="summary" id="summary" cols="" rows="" class="textarea" placeholder="说点什么...最多输入500个字符"
                    datatype="*10-100" dragonfly="true" onKeyUp="textarealength(this,500)">{$data.summary}</textarea>
                <p class="textarea-numberbar">
                    <em class="textarea-length">0</em>/500
                </p>
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">内容类型:</label>
            <div class="switch" data-on-label="富文本" data-off-label="源码" id="mySwitch">
                <input type="checkbox" {if $data.type==0}checked{/if} />
            </div>
            <input type="hidden" value="{$data.type}" name="type" id="content_type">
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <div class="formControls col-sm-10 col-sm-offset-1">
                <div id="content_type_0" {if $data.type==1}style="display: none;" {/if}>
                    <script id="editor" type="text/plain"
                        style="width:100%;height:400px;">{$data.content ? $data.content|raw : ''}</script>
                </div>
                <div id="content_type_1" {if $data.type==0}style="display: none;" {/if}>
                    <textarea name="content" id="content" cols="" rows="" class="textarea"
                        style="height: 400px;">{$data.content}</textarea>
                </div>
            </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <button type="button" class="btn btn-success radius" onclick="save();">确&nbsp;定</button>
                <button type="button" class="btn btn-default radius" onclick="window.history.back();"
                    style="margin-left:20px;">取&nbsp;消</button>
            </div>
        </div>
    </form>
    <!-- 标题图上传 -->
    <div>
        <form id="form-upload_picture">
            <input type="file" hidden name="image" id="upload_picture">
        </form>
    </div>
</article>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="/static/plugins/ckeditor/ckeditor5/ckeditor.js"></script>
<script type="text/javascript">
    $(function () {
        //实例化编辑器   
        ClassicEditor.create(document.querySelector('#editor'), {
            toolbar: {
                items: [
                    'sourceEditing', '|',
                    'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|',
                    'heading', '|',
                    'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', 'highlight', '|',
                    '-',
                    'alignment', 'outdent', 'indent', '|',
                    'undo', 'redo', '|',
                    'link', 'imageUpload', 'imageInsert', 'insertTable', '|',
                    'code', 'codeBlock', 'blockQuote', '|',
                    'findAndReplace', 'horizontalLine', 'numberedList', 'bulletedList',
                ],
                shouldNotGroupWhenFull: true
            },
            licenseKey: '',
            //图片上传
            simpleUpload: {
                // The URL the images are uploaded to.
                uploadUrl: '/sys/file_manager/ckeditorUploadImage'
            },
            //自定义字体
            fontFamily: {
                options: [
                    'default',
                    '微软雅黑,Microsoft YaHei',
                    '新宋体,NSimSun',
                    '楷体_GB2312,KaiTi_GB2312',
                    '黑体,SimHei',
                    '隶书,LiSu',
                    '幼园,YouYuan',
                    'Blackoak Std',
                    'Arial',
                    'Georgia',
                    'Tahoma',
                    'Trebuchet MS',
                    'verdana',
                ]
            },
            mediaEmbed: {   // 视频配置
                providers: [
                    {
                        name: 'myprovider',
                        url: [
                            /^suryee.*\.com.*\/(\w+)/,
                            /^www\.suryee.*/,
                            /^www\.bilibili.*/,
                            /(http|https):\/\/([\w.]+\/?)\S*/
                        ],
                        html: match => {
                            //获取媒体url
                            const input = match['input'];
                            return (
                                `<video src="${input}" controls="controls" style=" width: 100%;height: 100%; "></video>`
                            );
                        }
                    }
                ]
            }
        }).then(editor => {
            window.editor = editor;
        }).catch(error => {
            console.error('Oops, something went wrong!');
            console.error('Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:');
            console.warn('Build id: z4e2d8lqju9w-6lwv92tbu4hm');
            console.error(error);
        });
    })

    $('#mySwitch').on('switch-change', function (e, data) {
        var value = data.value;
        if (value === false) {
            $("#content_type").val(1);
            $("#content_type_0").css("display", "none");
            $("#content_type_1").css("display", "block");
        } else {
            $("#content_type").val(0);
            $("#content_type_0").css("display", "block");
            $("#content_type_1").css("display", "none");
        }
    });

    // 标题图上传
    const file = document.querySelector('input[type="file"]');

    function uploadPicture() {
        // file模拟input点击事件
        var evt = new MouseEvent("click", {
            bubbles: false,
            cancelable: true,
            view: window,
        });
        file.dispatchEvent(evt, uploadfn());
    }

    function uploadfn() {
        file.oninput = function () {
            if (file.files && file.files[0]) {
                var formData = new FormData();
                formData.append("upload_file", file.files[0]);
                $.ajax({
                    url: '{:url("/sys/file_manager/uploadImage")}',
                    type: "post",
                    data: formData,
                    processData: false, // 告诉jQuery不要去处理发送的数据
                    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                    dataType: 'json',
                    success: function (res) {
                        // console.log(res);
                        var img = res.data.filename;
                        $("#view-titlepic").attr('src', img);
                        $("#titlepic").val(img);
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 1000
                        });
                    },
                    error: function (res) {
                        layer.msg(res.msg, {
                            icon: 5,
                            time: 1000
                        });
                        return false;
                    },
                    complete: function () {
                        document.getElementById('form-upload_picture').reset();
                    }
                });
            }
        }
    }

    // 保存内容
    function save() {
        var content_type = $("#content_type").val();
        console.log(content_type);
        if (content_type == 0) {
            const content = window.editor.getData();

            $("#content").val(content);
        }

        var data = $("#form-save").serializeArray();

        $.ajax({
            type: 'POST',
            url: '{:url("/sys/industry_en/save")}',
            data: data,
            dataType: 'json',
            success: function (res) {
                // console.log(res);
                if (res.code == 0) {
                    layer.msg(res.msg, { icon: 1, time: 500 }, function () {
                        window.location.href = '/sys/industry_en/index';  // 返回列表页
                    });
                } else {
                    layer.msg(res.msg, { icon: 5, time: 1000 });
                    return false;
                }
            }
        })
    }
</script>